package cn.tedu.blog.server.security;


import cn.tedu.blog.server.mapper.UserMapper;
import cn.tedu.blog.server.pojo.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: 雷茂林
 * @Date:2022/7/15 22:14
 * @Description:
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        log.debug("Spring Security自动根据用户名【{}】查询用户详情", s);

        //执行查询
        UserLoginVO userLoginVO = userMapper.getByUsername(s);

        //判断是否查询到有效结果
        if (userLoginVO!=null){
            ///认证权限的集合需要时SimpleGrantedAuthority类型的
            List<SimpleGrantedAuthority> authorities = new ArrayList<>();
            for (String permission : userLoginVO.getPermissions()) {
                authorities.add(new SimpleGrantedAuthority(permission));
            }

            // 调用UserDetails类，注入用户认证信息
            //因为security框架没有ID的概念，所以自定义一个类封装ID属性，在处理登录成功时会返回这个自定义的实例对象
            UserDetails userDetails = new UserDetails(
                    userLoginVO.getUsername(),
                    userLoginVO.getPassword(),
                    userLoginVO.getStatus()==1,
                    authorities
            );
            log.debug("即将向自定义类写入ID：{}",userLoginVO.getId());
            userDetails.setId(userLoginVO.getId());
            return userDetails;
        }
        log.debug("没有查询到匹配的管理员信息");
        throw new BadCredentialsException("用户名或密码错误");
    }
}
